#!/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import print_function

import MySQLdb
import chardet

from proxyips.mysqlmoudel.sqlbuilder import MysqlBuilder
"""
这里我们采用  Abstract Factory模式 
"""

class Abssql:
    """
    返回一个sql工厂
    """
    @staticmethod
    def getsqlfractry():
        return SqlFractry()


class SqlFractry(Abssql):
    """
    返回一个mysql的对象
    """
    @staticmethod
    def mysqlFractry(type):
        if type == 'mysql':
            return Mysql()
        assert 0, "err sql type please check:" + type


class Mysql(SqlFractry):
    def __init__(self):
        self.db = ''
        self.cursor = ''

    def link(self, mysqlmoudle):
        print (mysqlmoudle['host'], mysqlmoudle['user'], mysqlmoudle['passwd'], mysqlmoudle['db'], mysqlmoudle['port'])
        self.db = MySQLdb.connect(str(mysqlmoudle['host']), str(mysqlmoudle['user']), str(mysqlmoudle['passwd']), str(mysqlmoudle['db']),mysqlmoudle['port'],charset="utf8")
        self.cursor = self.db.cursor()
        return self.db, self.cursor

    def close(self):
        self.db.close()

class Mysql_util:
    def __init__(self):
        self.mysql = ''
        self.db = ''
        self.cursor = ''
        self.init()


    def init(self):
        self.mysql = Abssql.getsqlfractry().mysqlFractry("mysql")
        builder = MysqlBuilder('../config/mysql.ini', 'mysqllocalhost')
        moudle = builder.build_all().get_moudle().todict()
        #print(moudle)
        self.mysql.link(moudle)
        self.db = self.mysql.db
        self.cursor = self.mysql.cursor




if __name__ == "__main__":
    mysql = Abssql.getsqlfractry().mysqlFractry("mysql")
    builder = MysqlBuilder('../config/mysql.ini', 'mysqllocalhost')
    moudle = builder.build_all().get_moudle().todict()
    print(moudle)
    mysql.link(moudle)
    mysqlutil = Mysql_util()
    sql = "REPLACE INTO mws_proxy_ips (usetimes,Responsespeed,errtimes,ip,created_at,Finalverificationtime,updated_at,source,lapseTimes,anonymous,position,work,type,port) VALUES ('0','1秒','0','124.88.84.154','2017-10-13 15:25:52','2017-10-12 09:46:35','2017-10-13 15:25:52','1','0','透明','中国 新疆维吾尔自治区 乌鲁木齐市联通','1','HTTP','8080')".decode("utf-8")
    mysqlutil.cursor.execute(sql)
    mysqlutil.db.commit()


